﻿var items;

$(document).ready(function () {

    if (window.location.href.indexOf("?selectedItem=myTasks") < 0 &&
        window.location.href.indexOf("?selectedItem=allTasks") < 0 &&
        window.location.href.indexOf("?selectedItem=doneTasks") < 0) {
        window.location.href = "Tasks.aspx?selectedItem=myTasks";
    }
    if (window.location.href.indexOf("?selectedItem=myTasks") >= 0) {
        $("#myTasks a").css({ 'color': '#8EBD00' });
        $(".hTxt").text("Tasks > My Tasks");
        initMyTasks($.cookie("userId"));
    }
    else if (window.location.href.indexOf("?selectedItem=allTasks") >= 0) {
        $("#allTasks a").css({ 'color': '#8EBD00' });
        $(".hTxt").text("Tasks > All Tasks");
        initAllTasksFromGoals($.cookie("userId"));
    } else if (window.location.href.indexOf("?selectedItem=doneTasks") >= 0) {
        $("#doneTasks a").css({ 'color': '#8EBD00' });
        $(".hTxt").text("Tasks > Done Tasks");
        initMyDoneTasks($.cookie("userId"));
    }

    $("#taskSelection").change(function() {
        var status = $('#taskSelection').find(":selected").text();
        $(".td").remove();
        if (status == "All my tasks") {
            drawItems(items, "taskTable");
        } else if (status == "Assigned to me") {
            drawItems(getAssignedToMeItems(), "taskTable");
        } else if (status == "Created by me") {
            drawItems(getCreatedByMeItems(), "taskTable");
        }
    });

    $("#goalSelection").change(function () {
        var status = $('#goalSelection').find(":selected").text();
        $("#allTasksInGoals").empty();
        if (status == "From All Goals") {
            initStructureOfAllTasks(items);
        } else {
            initStructureOfAllTasks(getAllMyTasksInGoalStructure());
        }
    });
});

function getAllMyTasksInGoalStructure() {
    var userId = $.cookie("userId");
    var result = [];
    for (var i = 0; i < items.length; i++) {
        if (items[i].AssignedToId == userId || items[i].CreatedById == userId) {
            result.push(items[i]);
        }
    }
    return result;
}

function successShowUserTasks(data) {
    if (!showError(data)) {
        return;
    }
    items = $.parseJSON(data.Message);
    removeTasksFromItems(false); //removes all tasks with READY status
    sortItemsByPriority();
    drawItems(items, "taskTable");
}

function successShowAllTasks(data) { //Show all task according to each goal
    if (!showError(data)) {
        return;
    }
    items = $.parseJSON(data.Message);
    sortItemsByPriority();
    initStructureOfAllTasks(items);
}

function successShowuserDoneTasks(data) {
    if (!showError(data)) {
        return;
    }
    items = $.parseJSON(data.Message);
    removeTasksFromItems(true); //removes all tasks with NOT READY statuses
    sortItemsByPriority();
    drawItems(items, "taskTable");
}

function removeTasksFromItems(taskStatus) {
    for (var i = 0; i < items.length; i++) {
        if (taskStatus) {
            if (items[i].Status != "Ready") {
                items.splice(i, 1);
                i--;
            }
        } else {
            if (items[i].Status == "Ready") {
                items.splice(i, 1);
                i--;
            }
        }
    }
}

function drawItems(itemsToDraw, tableToDraw) {
    for (var i = 0; i < itemsToDraw.length; i++) {
        addItemToTable(itemsToDraw[i], i, tableToDraw);
    }
}

function getAssignedToMeItems() {
    var newItems = [];
    var myId = $.cookie("userId");
    for (var i = 0; i < items.length; i++) {
        if (items[i].AssignedToId == myId) {
            newItems.push(items[i]);
            continue;
        }
    }
    return newItems;
}

function getCreatedByMeItems() {
    var newItems = [];
    var myId = $.cookie("userId");
    for (var i = 0; i < items.length; i++) {
        if (items[i].CreatedById == myId) {
            newItems.push(items[i]);
            continue;
        }
    }
    return newItems;
}

function compare(a, b) {
    if (a.PriorityVal < b.PriorityVal)
        return -1;
    if (a.PriorityVal > b.PriorityVal)
        return 1;
    return 0;
}

function sortItemsByPriority() {
    items.sort(compare);
}

function addItemToTable(item, number, table) {
    $("<tr/>", {
        id: 'tr-' + number,
        class: "td " + (((number + 1) % 2) ? "" : "odd")
    }).appendTo("#"+table);

    $("<td/>", {
        id: "taskId-" + number
    }).appendTo('#tr-' + number).text(item.Id).css({'display':'none'});

    $("<td/>", {}).appendTo('#tr-' + number).text(number + 1);

    $("<td/>", {
        id: "taskName-" + number
    }).appendTo('#tr-' + number);
    
    $("<a/>", {
        href: "SelectedTask.aspx?taskId=" + item.Id,
        class: "refToSelectedTask"
    }).appendTo("#taskName-" + number).text(item.Name);

    $("<td/>", {}).appendTo('#tr-' + number).text(item.CreatedByName);

    $("<td/>", {}).appendTo('#tr-' + number).text(item.AssignedToName);

    $("<td/>", {}).appendTo('#tr-' + number).text(item.StartDate);

    $("<td/>", {}).appendTo('#tr-' + number).text(item.FinishDate);

    $("<td/>", {
        id: "taskPriority-" + number
    }).appendTo('#tr-' + number).text(item.PriorityStr);

    $("<td/>", {
        id: "taskStatus-" + number,
        class: "statusColumn"
    }).appendTo('#tr-' + number).text(item.Status);
}

function showError(data) {
    if (data.Status == "error") {
        showExceptionPop("Error", data.Message);
        return false;
    }
    else if (data.Status == "server_error") {
        showExceptionPop("Server Error", "Server error. Please try again later.");
        return false;
    }
    return true;
}

function containsGoal(goalName, goalArray) {
    for (var i = 0; i < goalArray.length; i++) {
        if (goalArray[i] == goalName) {
            return true;
        }
    }
    return false;
}

function initStructureOfAllTasks(itemsToDraw) {
    var goals = [];
    for (var i = 0; i < itemsToDraw.length; i++) {
        if (!containsGoal(itemsToDraw[i].GoalName, goals)) {
            goals.push(itemsToDraw[i].GoalName);
        }
    }
    for (i = 0; i < goals.length; i++) {
        drawAllTasks(getTasksByGoalName(goals[i], itemsToDraw), goals[i], i);
    }
}

function getTasksByGoalName(goalName, itemsToChoose) {
    var tasks = [];
    for (var i = 0; i < itemsToChoose.length; i++) {
        if (itemsToChoose[i].GoalName == goalName) {
            tasks.push(itemsToChoose[i]);
        }
    }
    return tasks.sort(compare);
}

function drawAllTasks(tasks, goalName, number) {
    $("<div/>", {
        id: "goal-"+number
    }).appendTo("#allTasksInGoals");

    $("<div/>", {
        id: "goalNameHeader-" + number,
        class: "goalnameHeader"
    }).appendTo("#goal-" + number).text(goalName);

    $("<table/>", {
        id: "taskTable-" + number,
        class: "tasksTable"
    }).appendTo("#goal-" + number).attr("cellspacing", "0");

    $("<tr/>", {
        id: "taskTableHeader-" + number,
        class: "taskTableHeader"
    }).appendTo("#taskTable-" + number);

    $("<th/>").appendTo("#taskTableHeader-" + number).text("Number");
    $("<th/>").appendTo("#taskTableHeader-" + number).text("Name");
    $("<th/>").appendTo("#taskTableHeader-" + number).text("Created by");
    $("<th/>").appendTo("#taskTableHeader-" + number).text("Assigned to");
    $("<th/>").appendTo("#taskTableHeader-" + number).text("Start date");
    $("<th/>").appendTo("#taskTableHeader-" + number).text("Finish date");
    $("<th/>").appendTo("#taskTableHeader-" + number).text("Priority");
    $("<th/>").appendTo("#taskTableHeader-" + number).text("Status");
    
    for (var i = 0; i < tasks.length; i++) {
        addItemsToGoal("#taskTable-" + number, i, tasks[i], number);
    }
}

function addItemsToGoal(tableName, number, item, tableNumber) {
    $("<tr/>", {
        id: "tr-" + tableNumber + "-" + number,
        class: "td " + (((number + 1) % 2) ? "" : "odd")
    }).appendTo(tableName);

    $("<td/>", {
        id: "taskId-" + tableNumber + "-" + number
    }).appendTo("#tr-" + tableNumber + "-" + number).text(item.Id).css({ 'display': 'none' });

    $("<td/>", {}).appendTo("#tr-" + tableNumber + "-" + number).text(number + 1);

    $("<td/>", {
        id: "taskName-" + tableNumber + "-" + number
    }).appendTo("#tr-" + tableNumber + "-" + number);

    $("<a/>", {
        href: "SelectedTask.aspx?taskId=" + item.Id,
        class: "refToSelectedTask"
    }).appendTo("#taskName-" + tableNumber + "-" + number).text(item.Name);

    $("<td/>", {}).appendTo("#tr-" + tableNumber + "-" + number).text(item.CreatedByName);

    $("<td/>", {}).appendTo("#tr-" + tableNumber + "-" + number).text(item.AssignedToName);

    $("<td/>", {}).appendTo("#tr-" + tableNumber + "-" + number).text(item.StartDate);

    $("<td/>", {}).appendTo("#tr-" + tableNumber + "-" + number).text(item.FinishDate);

    $("<td/>", {
        id: "taskPriority-" + tableNumber + "-" + number
    }).appendTo("#tr-" + tableNumber + "-" + number).text(item.PriorityStr);

    $("<td/>", {
        id: "taskStatus-" + tableNumber + "-" + number,
        class: "statusColumn"
    }).appendTo("#tr-" + tableNumber + "-" + number).text(item.Status);
}